const {
  createOrUpdate,
  findCarts,
  updateCarts,
  removeCarts,
  selectAllCarts,
  unselectAllCarts
} = require("../service/cartsService");
const {
  addCartsError,
  cartFormatError,
  internalServerError,
} = require("../constant/error");

class CartController {
  async add(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const goods_id = ctx.request.body.goods_id;

      const res = await createOrUpdate(user_id, goods_id);

      ctx.body = {
        code: 0,
        msg: "添加购物车成功",
        result: res,
      };
    } catch (err) {
      console.error("添加购物车失败:", err);
      return ctx.app.emit("error", addCartsError, ctx);
    }
  }

  async findAll(ctx) {
    try {
      const { pageNum = 1, pageSize = 10 } = ctx.request.body;
      const res = await findCarts(pageNum, pageSize);
      ctx.body = {
        code: 0,
        msg: "获取购物车列表成功",
        result: res,
      };
    } catch (error) {
      console.error("Error in findAll:", error);
      ctx.app.emit("error", internalServerError, ctx);
    }
  }

  async update(ctx) {
    try {
      const { id } = ctx.request.params;
      const { number, selected } = ctx.request.body;
      if (number === undefined && selected === undefined) {
        cartFormatError.msg = "number 和 selected 不能同时为空";
        return ctx.app.emit("error", cartFormatError, ctx);
      }
      const res = await updateCarts({ id, number, selected });
      ctx.body = {
        code: 0,
        msg: "更新购物车成功",
        result: res,
      };
    } catch (error) {
      console.error("Error in update:", error);
      ctx.app.emit("error", internalServerError, ctx);
    }
  }

  async remove(ctx) {
    try {
      const { ids } = ctx.request.body;
      const res = await removeCarts(ids);
      ctx.body = {
        code: 0,
        msg: "删除购物车成功",
        result: res,
      };
    } catch (error) {
      console.error("Error in remove:", error);
      ctx.app.emit("error", internalServerError, ctx);
    }
  }

  async selectAll(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const res = await selectAllCarts(user_id);
      ctx.body = {
        code: 0,
        msg: "全选购物车成功",
        result: res,
      };
    } catch (error) {
      console.error("Error in selectAll:", error);
      ctx.app.emit("error", internalServerError, ctx);
    }
  }

  async unselectAll(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const res = await unselectAllCarts(user_id);
      ctx.body = {
        code: 0,
        msg: "全不选购物车成功",
        result: res,
      };
    } catch (error) {
      console.error(error);
      ctx.app.emit("error", internalServerError, ctx);
    }
  }

}

module.exports = new CartController();
